#!/sbin/openrc-run

description="Step CA"
description_setup="Initialise configuration"
description_checkconfig="Verify configuration"
description_reload="Reload configuration"

config_dir="/etc/step-ca"
log_dir="/var/log/step-ca"
error_log="${log_dir}/${RC_SVCNAME}.log"
profile_file="${config_dir}/.profile"
ca_file="${config_dir}/config/ca.json"
passwd_file="${config_dir}/password.txt"

export STEPPATH="${config_dir}"

command_background="yes"
command="/usr/bin/step-ca"
command_user="step-ca:step-ca"
command_args="${ca_file} --password-file=${passwd_file} ${command_args}"
extra_commands="reload checkconfig setup"
pidfile="/run/$RC_SVCNAME.pid"

depend() {
        use logger dns
        after entropy networking
}

setup() {
        step ca init "${setup_args}"
        printf '\n'
        einfo "Copy your password into: ${passwd_file}"
}

reload() {
        ebegin "Reloading ${RC_SVCNAME}"
        if [ "$supervisor" ]; then
                ${supervisor} ${RC_SVCNAME} --signal HUP --pidfile "${pidfile}"
        else
                start-stop-daemon --pidfile "$pidfile" --signal HUP
        fi
        eend $?
}

start_pre() {
        checkconfig
}

checkconfig() {
        if [ ! -f ${ca_file} ]; then
                eend "CA configuration is missing: ${ca_file}"
                eend "Generate configuration with: /etc/init.d/$RC_SVCNAME setup"
                exit 1
        fi

        if [ ! -f ${passwd_file} ]; then
                eend "${passwd_file} is missing"
                exit 1
        fi

        if [ ! -f ${profile_file} ]; then
                install -dm700 ${config_dir}
                printf "%s\n" "export STEPPATH=$config_dir" > ${profile_file}
        fi

        if [ ! -d ${log_dir} ]; then
                install -dm700 ${log_dir}
        fi

        chown -R ${command_user} ${config_dir}
        chown -R ${command_user} ${log_dir}
        chmod 400 ${passwd_file}
}
